<?php
set_time_limit(0);
require_once '../system/common.inc.php';
require_once '../system/class/getid3/getid3.php';
if($uid){
	$targetFile = mktime();
	$opts = array(
		'http'=>array(
			'method'=>"GET",
			'header'=>"User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
		)
	);
	$context = stream_context_create($opts);
	$url = $_GET['downurl'];
	$data = file_get_contents($url,false,$context);
	preg_match("/name=.httpfileurl..content=.(.*?).>/", $data, $data);
	$myurl = $data[1];
	if($myurl){
		$fc = file_get_contents($myurl);
		file_put_contents($targetFile,$fc);
		$getID3 = new getID3();
		$FileInfo = $getID3->analyze($targetFile);
		if($FileInfo['fileformat'] == 'mp3'){
			$bitrate     = $FileInfo['audio']['bitrate'];
			$id3 = array();
			if($FileInfo['tags']['id3v2']){
				$title  = $FileInfo['tags']['id3v2']['title']['0'];
				$artist = $FileInfo['tags']['id3v2']['artist']['0'];
				$album  = $FileInfo['tags']['id3v2']['album']['0'];
				$id3 = array('title'=>$title,'artist'=>$artist,'album'=>$album);
			}else{
				$id3 = array();
			}
		}elseif($FileInfo['fileformat'] == 'flac'){
			$bitrate     = $FileInfo['audio']['bitrate'];
			$id3 = array();
			$title  = $FileInfo['tags']['vorbiscomment']['title']['0'];
			$artist = $FileInfo['tags']['vorbiscomment']['artist']['0'];
			$album  = $FileInfo['tags']['vorbiscomment']['album']['0'];
			$id3 = array('title'=>$title,'artist'=>$artist,'album'=>$album);
		}else exit('<script>alert("File Format is not supported");</script>');
		$encode = mb_detect_encoding($id3['title']);
		if($encode != 'UTF-8') $str = iconv($encode,'UTF-8',$id3['title']);
		$id3['title'] = trim($id3['title']);
		$encode = mb_detect_encoding($id3['artist']);
		if($encode != 'UTF-8') $str = iconv($encode,'UTF-8',$id3['artist']);
		$id3['artist'] = trim($id3['artist']);
		$encode = mb_detect_encoding($id3['album']);
		if($encode != 'UTF-8') $str = iconv($encode,'UTF-8',$id3['album']);
		$id3['album'] = trim($id3['album']);
		if($FileInfo['fileformat']=='flac') $type = '3';
		elseif(intval($bitrate) >= 320000) $type = '2';
		else $type = '1';
	}else{
		$type = '0';
	}
	$fid = explode('/',$url);
	$fid = end($fid);
	DB::insert('songs', array(
		'uid' => $uid,
		'title' => ($id3['title'] ? $id3['title'] : '未知[获取失败]'),
		'artist' => ($id3['artist'] ? $id3['artist'] : '未知[获取失败]'),
		'album' => ($id3['album'] ? $id3['album'] : '未知[获取失败]'),
		'status' => '1',
		'type' => $type,
		'fileserver_type' => 'vdisk',
		'fileserver_data' => $fid,
	));
	unlink($targetFile);
	echo "<script>alert('上传成功！');opener.location.href='/my.php';window.close();</script>";
}else exit("Access Denied");
?>